﻿using Microsoft.AspNetCore.Mvc;
using System;
using ZhCun.WebTemplate.AL;
using ZhCun.Utils.Helpers;
using ZhCun.WebCommon;
using ZhCun.WebCommon.AL;
using ZhCun.WebCommon.ApiModels;
using ZhCun.WebCommon.ViewModels;
using ZhCun.WebCommon.WebApi;

namespace ZhCun.WebTemplate.Web.ApiControllers
{
    public class ApiUserController : ApiUserBaseController<ALUser>
    {
        private readonly static string VerifyCode_SessionKey = "{A46A6F1C-1230-45F9-A016-CC14165B17F9}";

        /// <summary>
        /// api 用户登陆
        /// </summary>
        [HttpPost]
        [NonLoginVerify]
        [Route("/api/login")]
        public ApiResult ApiLogin(UserBaseArgLogin arg)
        {
            return base.Login(arg);
        }
        /// <summary>
        /// 用户登陆
        /// </summary>
        [HttpPost]
        [NonLoginVerify]
        [Route("/page/login")]
        public ApiResult PageLogin(UserBaseArgLogin arg)
        {
            if (arg == null)
            {
                return CreateResult(false, "参数有误");
            }
            if (string.IsNullOrWhiteSpace(arg.VerifyCode))
            {
                return CreateResult(false, "验证码不能为空");
            }
            var code = HttpContext.GetSession(VerifyCode_SessionKey);
            if (!arg.VerifyCode.Equals(code, StringComparison.CurrentCultureIgnoreCase))
            {
                HttpContext.Session.Remove(VerifyCode_SessionKey);
                return CreateResult(false, "验证码错误");
            }
            //登录模式 1：webapi 2:web page ,100:权限管理网页登录
            var tokenTimeout = AppCommonConfig.AppSettings.TokenTimeOutByPage;
            //登录模式为100，表示权限管理登录，只有管理员可登录(RolId='000')
            if (ALObj.Login(arg.LoginName, arg.LoginPwd, tokenTimeout, 2, HttpContext.Session.Id, out string msg))
            {
                HttpContext.SetCookie(Constants.TOKEN_NAME, ALObj.LoginUser.LoginToken, ALObj.LoginUser.LoginExpiresTime);
                return CreateResult(true, "登陆成功");
            }
            else
            {
                return CreateResult(false, msg);
            }
        }
        /// <summary>
        /// 获取登录验证码
        /// </summary>
        [NonLoginVerify]
        [HttpGet]
        public IActionResult GetLoginVerifyCode()
        {
            var img = ImageHelper.GetVerifyCodeToBytes(130, 39, 5, out string code);
            HttpContext.SetSession(VerifyCode_SessionKey, code);
            return File(img, @"image/jpeg");
        }        
    }
}